package com.aliang.chat.service;

import com.aliang.chat.mapper.ContactMapper;
import com.aliang.chat.mapper.UserMapper;
import com.aliang.chat.model.dto.ContactDTO;
import com.aliang.chat.model.entity.Contact;
import com.aliang.chat.model.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ContactService {
    @Resource
    private ContactMapper contactMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 根据用户id查询联系人
     * @param userId
     * @return
     */
    public List<ContactDTO> getContactList(Integer userId) {
        //根据用户id查询用户数据
        List<Contact> contacts = contactMapper.selectContactByUserId(userId);
        if (contacts.size() == 0 ) {
            return null;
        }
        //获取所有联系人的用户id
        List<Integer> ids = contacts.stream().map(Contact::getId).collect(Collectors.toList());
        //根据用户id查询数据
        List<User> contactsUser = userMapper.selectByUserIds(ids);
        //根据id集合查询数据
        Map<Integer, User> userMap = contactsUser.stream().collect(Collectors.toMap(User::getId, user -> user));
        //转化为vo
        List<ContactDTO> contactDTOS = new ArrayList<>();
        contacts.forEach(contact -> {
            ContactDTO contactDTO = new ContactDTO();
            BeanUtils.copyProperties(contact, contactDTO);
            //根据用户Id获取用户数据
            User user = userMap.get(contact.getId());
            contactDTO.setDisplayName(user.getDisplayName());
            contactDTO.setAvatar(user.getAvatar());
            contactDTOS.add(contactDTO);
        });

        return contactDTOS;
    }


    public void addOrUpdateContact(ContactDTO contactDTO, Integer userId) {
        Contact contact = contactMapper.selectByUserIdAndContactId(userId, contactDTO.getId());
        BeanUtils.copyProperties(contactDTO,contact);
        //为null，不存在，新增联系人
        if (contact.getContactId() == null) {
            //封装数据
            contact = new Contact();
            contact.setUserId(userId);
            //保存用户的联系人数据
            contactMapper.add(contact);
            //同步添加联系人的用户数据
            contact.setId(userId);
            contact.setUserId(contactDTO.getId());
            contactMapper.add(contact);
        } else {
            //不为null,更新信息和时间戳
            contactMapper.updateByUserIdOrContactId(contact);
        }

    }
}
